package service

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"service/basic/global"
	__ "service/basic/proto"
	"service/internal/model"
	"time"
)

type Service struct {
	__.UnimplementedPetServer
}

func (s *Service) BeautyList(_ context.Context, req *__.BeautyListReq) (resp *__.BeautyListResp, err error) {
	var beauties []model.Beauty
	global.DB.Debug().Model(&model.Beauty{}).Find(&beauties)

	var beautyList []*__.BeautyItem
	for _, beauty := range beauties {
		list := __.BeautyItem{
			CoverUrl:  beauty.CoverUrl,
			Title:     beauty.Title,
			Introduce: beauty.Introduce,
			Price:     float32(beauty.Price),
		}
		beautyList = append(beautyList, &list)
	}

	resp = &__.BeautyListResp{
		List: beautyList,
	}

	data, err := json.Marshal(resp)
	if err != nil {
		return nil, err
	}

	global.Rdb.Set(global.Ctx, "pet_beauty_list", data, time.Minute*5)

	return resp, nil
}

func (s *Service) BeautyDetailList(_ context.Context, req *__.BeautyDetailListReq) (resp *__.BeautyDetailListResp, err error) {
	var combos []model.ComboDetail
	global.DB.Debug().Model(&model.ComboDetail{}).Where("beauty_id = ?", req.BeautyId).Find(&combos)

	var beautyList []*__.BeautyDetailItem
	for _, combo := range combos {
		list := __.BeautyDetailItem{
			Id:        combo.BeautyId,
			BeautyId:  combo.BeautyId,
			CoverUrl:  combo.CoverUrl,
			Title:     combo.Title,
			PetId:     combo.PetId,
			AddressId: combo.AddressId,
			Store:     combo.Store,
			Introduce: combo.Introduce,
		}
		beautyList = append(beautyList, &list)
	}

	resp = &__.BeautyDetailListResp{
		List: beautyList,
	}

	data, err := json.Marshal(resp)
	if err != nil {
		return nil, err
	}

	global.Rdb.Set(global.Ctx, "pet_beauty_detail", data, time.Minute*5)

	return resp, nil
}

func (s *Service) PetList(_ context.Context, req *__.PetListReq) (resp *__.PetListResp, err error) {
	var pets []model.Pet
	global.DB.Debug().Model(&model.Pet{}).Find(&pets)

	var petList []*__.PetItem
	for _, pet := range pets {
		list := __.PetItem{
			Id:       int64(pet.ID),
			Avatar:   pet.Avatar,
			Name:     pet.Name,
			Category: pet.Category,
			Sex:      pet.Sex,
			Age:      pet.Age,
			Status:   pet.Status,
		}
		petList = append(petList, &list)
	}

	resp = &__.PetListResp{
		List: petList,
	}

	return resp, nil
}

func (s *Service) PetAdd(_ context.Context, req *__.PetAddReq) (resp *__.PetAddResp, err error) {
	pets := model.Pet{
		Avatar:   req.Avatar,
		Name:     req.Name,
		Category: req.Category,
		Sex:      req.Sex,
		Age:      req.Age,
		Status:   req.Status,
	}

	err = global.DB.Debug().Create(&pets).Error
	if err != nil {
		return nil, fmt.Errorf("宠物信息添加失败")
	}

	resp = &__.PetAddResp{
		Id:      int64(pets.ID),
		Success: true,
		Message: "宠物信息添加成功",
	}

	return resp, nil
}

func (s *Service) AddressList(_ context.Context, req *__.AddressListReq) (resp *__.AddressListResp, err error) {
	var addresses []model.Address
	global.DB.Debug().Model(&model.Address{}).Find(&addresses)

	var addressList []*__.AddressItem
	for _, address := range addresses {
		list := __.AddressItem{
			Id:   int64(address.ID),
			Name: address.Name,
		}
		addressList = append(addressList, &list)
	}

	resp = &__.AddressListResp{
		List: addressList,
	}

	return resp, nil
}

func (s *Service) CreateOrder(_ context.Context, req *__.CreateOrderReq) (resp *__.CreateOrderResp, err error) {

	if req.UserId == 0 || req.BeautyId == 0 || req.Waiter == "" || req.Time == "" {
		return nil, fmt.Errorf("请完善订单信息")
	}

	order := model.Order{}
	global.DB.Debug().Where("order_sn = ?", req.OrderSn).First(&order)
	if order.ID != 0 {
		return nil, fmt.Errorf("当前订单尚未过期，请前往支付")
	}

	if req.Quantity > 50 {
		return nil, fmt.Errorf("当前套餐库存不足，请重新选择")
	}

	orderSn := GetOrderSn()

	order = model.Order{
		UserId:    req.UserId,
		BeautyId:  req.BeautyId,
		BeginTime: req.Time,
		Waiter:    req.Waiter,
		Content:   req.Content,
		Remarks:   req.Remarks,
		Price:     float64(req.Price),
		OrderSn:   orderSn,
		Quantity:  req.Quantity,
	}

	err = global.DB.Debug().Create(&order).Error
	if err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}

	resp = &__.CreateOrderResp{
		Id:      int64(order.ID),
		Success: true,
		Message: "订单创建成功",
	}
	return resp, nil
}

func GetOrderSn() string {
	str := uuid.New().String()
	return str
}
